package register;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetDataCallback;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.SignUpCallback;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import co.yeye.test.MainActivity;
import co.yeye.test.R;

/**
 * Created by yeye on 15/2/16.
 */
public class register extends Activity{

    EditText username,code,name,email,pwk,pwk_confirm,phone;
    Button tittle,btn_confirm;
    ImageView img;
    String img_file_path="-1",img_file_name="-1";
    ImageLoader imageLoader;
    DisplayImageOptions options;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        imageLoader = MainActivity.getInstance().getImageLoader();
        options = MainActivity.getInstance().getOptionCache();

        username = (EditText) findViewById(R.id.username);
        code = (EditText) findViewById(R.id.code);
        name = (EditText) findViewById(R.id.name);
        email = (EditText) findViewById(R.id.email);
        pwk = (EditText) findViewById(R.id.pwk);
        pwk_confirm = (EditText) findViewById(R.id.pwk_confirm);
        phone = (EditText) findViewById(R.id.phone);
        tittle = (Button) findViewById(R.id.tittle);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);
        img = (ImageView) findViewById(R.id.register_img);

        tittle.setVisibility(View.GONE);

        setBtnListener();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode==100){
                String sdStatus = Environment.getExternalStorageState();
                if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                    Log.i("TestFile",
                            "SD card is not avaiable/writeable right now.");
                    return;
                }
                String name = new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
                Toast.makeText(this, name, Toast.LENGTH_LONG).show();
                Bundle bundle = data.getExtras();
                Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式

                FileOutputStream b = null;
                File file = new File("/sdcard/myImage/");
                file.mkdirs();// 创建文件夹
                String fileName = "/sdcard/myImage/"+name;
                img_file_path = fileName;
                img_file_name = name;

                try {
                    b = new FileOutputStream(fileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        b.flush();
                        b.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                imageLoader.displayImage("file://"+fileName,img,options,null);
                //img.setImageBitmap(bitmap);// 将图片显示在ImageView里
            }
        }
        if(resultCode==RESULT_OK){
            if(requestCode==101){
                img_file_path = data.getData().toString();
                imageLoader.displayImage(img_file_path,img,options,null);
                img_file_path = GetPathByUri.getPath(getBaseContext(), data.getData());
                img_file_name = "head";
            }
        }
    }

    private void setBtnListener(){
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 让用户选择拍照还是本地选取图片
                AlertDialog alertDialog = new AlertDialog.Builder(register.this)
                        .setTitle("选择图片来源")
                        .setNegativeButton("拍照",new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(intent,100);
                            }
                        })
                        .setPositiveButton("图库",new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                intent.setType("image/*");
                                intent.putExtra("crop", "true");
                                intent.putExtra("aspectX", 1);
                                intent.putExtra("aspectY", 1);
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 101);
                            }
                        })
                        .show();
            }
        });

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(code.getText().length()==0 || name.getText().length()==0 ||
                        email.getText().length()==0 || pwk.getText().length()==0 ||
                        pwk_confirm.getText().length()==0 || username.getText().length()==0 ||
                        phone.getText().length()==0){
                    setTittle("请输入必要的信息",Color.parseColor("#f0485b"),3000,false);
                    return;
                }
                if(!isEmail(email.getText().toString())) {
                    setTittle("邮箱格式错误", Color.parseColor("#f0485b"), 3000,false);
                    return;
                }
                if(!pwk.getText().toString().equals(pwk_confirm.getText().toString())) {
                    setTittle("两次输入的密码不相同", Color.parseColor("#f0485b"), 3000,false);
                    return;
                }
                if(!isMobileNum(phone.getText().toString())){
                    setTittle("电话号码格式错误", Color.parseColor("#f0485b"), 3000,false);
                    return;
                }
                if(img_file_name.equals("-1")){
                    setTittle("请配置头像", Color.parseColor("#f0485b"), 3000,false);
                    return;
                }

                setTittle("正在注册",Color.parseColor("#6df767"),0,false);

                // 验证学号和姓名是否对应
                AVQuery<AVObject> query = new AVQuery<AVObject>("UserDB");
                query.whereEqualTo("code", code.getText().toString());
                query.findInBackground(new FindCallback<AVObject>() {
                    public void done(List<AVObject> avObjects, AVException e) {
                        if (e == null) {
                            //Toast.makeText(getBaseContext(),avObjects.get(0).toString(),Toast.LENGTH_SHORT).show();
                            if (!avObjects.get(0).getString("name").equals(name.getText().toString()))
                                setTittle("学号或名称错误", Color.parseColor("#f5a85d"), 3000,false);
                            else if (avObjects.get(0).getBoolean("signed"))
                                setTittle("该用户已注册", Color.parseColor("#f5a85d"), 3000,false);
                            else {
                                sign(avObjects.get(0),
                                        username.getText().toString(), pwk.getText().toString(),
                                        email.getText().toString());
                                //setTittle("注册成功", Color.parseColor("#55de30"), 3000);
                            }
                            //Log.d("成功", "查询到" + avObjects.size() + " 条符合条件的数据");
                        } else {
                            //Toast.makeText(getBaseContext(),e.toString(),Toast.LENGTH_SHORT).show();
                            //Log.v("YeYe",e.toString());
                            if(e.toString().equals("com.avos.avoscloud.AVException: Wrong response content type:null"))
                                setTittle("网络异常", Color.parseColor("#f5a85d"), 3000,false);
                            else
                                setTittle("请确认您学号和名称的准确性", Color.parseColor("#f5a85d"), 3000,false);
                        }
                    }
                });

            }
        });

    }

    private void sign(final AVObject object , final String username , String pwk ,String email ){
        SaveCallback callback = new SaveCallback() {
            @Override
            public void done(AVException e) {
                AVFile file = object.getAVFile("user_img");
                String url = file.getUrl();
                // 保存文件路径
                SharedPreferences sharedPreferences = getSharedPreferences("MyOpto", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor;
                editor = sharedPreferences.edit();
                String user_code = code.getText().toString();
                editor.putBoolean("isLogin",true);
                editor.putString("user_name",username);
                editor.putString("user_code",user_code);
                editor.putString(user_code+"_img_uri",url);
                editor.commit();

                /*
                Intent intent = new Intent();
                intent.putExtra("path",url);
                intent.putExtra("name",username);
                intent.putExtra("code",code.getText().toString());
                setResult(RESULT_OK, intent);
                */
                Toast.makeText(getBaseContext(),"注册成功，请登录",Toast.LENGTH_SHORT).show();
                // 跳转登录页面
                Intent intent = new Intent(register.this,Login.class);
                startActivity(intent);

                finish();

                //setTittle("注册成功", Color.parseColor("#55de30"), 1000, true);
            }
        };

        /*
        object.put("username", username);
        object.put("password", pwk);
        object.put("email", email);
        object.put("signed",true);
        object.put("imguri",img_file_name);
        // 保存头像
        if(!img_file_name.equals("-1")){
            AVFile avFile = new AVFile();
            try {
                avFile = AVFile.withAbsoluteLocalPath(img_file_name, img_file_path);
                object.put("user_img",avFile);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        else
            return;
        object.saveInBackground(callback );
        */

        // 使用AVUser保存
        AVUser avUser = new AVUser();
        avUser.setUsername(username);
        avUser.setPassword(pwk);
        avUser.setEmail(email);
        avUser.setMobilePhoneNumber(phone.getText().toString());
        avUser.put("name",name.getText().toString());
        avUser.put("user_ID",code.getText().toString());
        //avUser.put("imguri",img_file_name);
        if(!img_file_name.equals("-1")){
            AVFile avFile = new AVFile();
            try {
                avFile = AVFile.withAbsoluteLocalPath(img_file_name, img_file_path);
                avUser.put("user_img",avFile);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        avUser.signUpInBackground(new SignUpCallback() {
            @Override
            public void done(AVException e) {
                if(e==null){
                    // 还需要告诉UserDB该用户已存在
                    object.put("signed",true);
                    object.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(AVException e) {
                            Toast.makeText(getBaseContext(),"注册成功，请登录",Toast.LENGTH_SHORT).show();
                            // 跳转登录页面
                            Intent intent = new Intent(register.this,Login.class);
                            startActivity(intent);
                            finish();
                        }
                    });
                }
                else{
                    setTittle("用户名重复或网络错误，请修正",
                            getResources().getColor(R.color.red),3000,false);
                }
            }
        });

    }

    /**
     * 配置顶部的按钮
     */
    private void setTittle( String text , int color , int time , final boolean isGone ){
        tittle.setText(text);
        tittle.setBackgroundColor(color);
        tittle.setVisibility(View.VISIBLE);

        if(time!=0) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tittle.setVisibility(View.GONE);
                    if (isGone)
                        finish();
                }
            }, time);
        }

    }

    private boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\." +
                ")|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    private boolean isMobileNum(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "---");
        return m.matches();

    }

}
